package com.android.bookgarden.db;

import android.content.Context;

import org.xutils.DbManager;
import org.xutils.x;

import java.io.File;

/**
 * Created by zouqh on 2018/4/19.
 */

public class XutilsDB {
    private Context context;

    // 本类的单例实例
    private static XutilsDB instance;
    private DbManager.DaoConfig daoConfig;
    public DbManager dbManager;
    public static final String DATABASE_NAME = "realtimebs.db";

    // 获取本类单例对象的方法
    public static synchronized XutilsDB getInstance(Context context) {
        if (instance == null) {
            synchronized (XutilsDB.class) {
                if (instance == null) {
                    instance = new XutilsDB(context);
                }
            }
        }
        return instance;
    }

    public XutilsDB(Context context){
        this.context = context;
        setDB();
    }
    private void setDB() {
        File filesDir = context.getFilesDir();
        String filePath = filesDir.getAbsolutePath() + "/"+DATABASE_NAME;
        daoConfig = new DbManager.DaoConfig().setDbName(DATABASE_NAME)
                .setDbDir(new File(getFilePath(filePath)))
                .setDbVersion(1)
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {

                    }
                });
        dbManager = x.getDb(daoConfig);
    }

    public static String getFilePath(String sFileName) {
        return sFileName.substring(0, sFileName.lastIndexOf("/"));
    }
}
